package com.alan.camunda.boot.controller;


import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.Job;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/jobs")
public class JobController {

    @Resource
    private ManagementService managementService;


    /**
     * 查找所有失败的任务
     * @return
     */
    @GetMapping("/list-failed-jobs")
    public String listFailedJobs() {

        List<Job> failedJobs = managementService.createJobQuery().withException().list();

        List<Map<String, Object>> list = failedJobs.stream().map(job -> {
            Map<String, Object> data = new HashMap<>();
            data.put("id", job.getId());
            data.put("FailedActivityId", job.getFailedActivityId());
            data.put("message", job.getExceptionMessage());
            data.put("processInstanceId", job.getProcessInstanceId());
            data.put("retries", job.getRetries());
            return data;
        }).toList();

        return JSON.toJSONString(list);
    }


    /**
     * 查找所有失败的任务
     * @return
     */
    @GetMapping("/retry-failed-job")
    public String listFailedJobs(String jobId) {

        String stackTrace = managementService.getJobExceptionStacktrace(jobId);
        log.info(stackTrace);
        managementService.setJobRetries(jobId, 1);

        return "success";
    }

}
